package com.hc.common.filter;

import com.hc.common.constant.MDCKey;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.UUID;

/**
 *  设置链路追踪的值,方便日志查询
 */
@WebFilter(urlPatterns = "/*")
@Configuration
public class HttpTraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String tid = UUID.randomUUID().toString();
        try {
            MDC.put(MDCKey.TID, tid);
            chain.doFilter(request, response);
        }finally {
            MDC.remove(MDCKey.TID);
        }
    }
}